/*
 * ZBrowser is an embeddable browser component.
 * Copyright (C) Author: Gangadhar Nagesh Metla (Novell, Inc.)
 * nmetla74@gmail.com 
 * Version 1.0
 * 1/3/2009
 * Filename MessageBoxLauncher.java
 * 
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
 */

package com.novell.zenworks.agent.zbrowser;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.Locale;

import com.novell.zenworks.agent.common.ICommonUIEnums.MB_ICON;
import com.novell.zenworks.agent.common.ICommonUIEnums.MB_RESPONSE;
import com.novell.zenworks.agent.common.ICommonUIEnums.MB_TYPE;
import com.novell.zenworks.zicon.common.LogUtil;

public class MessageBoxLauncher
{
    public static final int NUM_JAVA_PARAMS = 10; //Number of JVM params.

    /**
     * @method This method will set display to 0.0 and the linux execution environment.
     * @throws IOException and InterruptedException
     *
     * @return String array of execution environment.
     */
    public static String[] setLinuxExecutionEnvironment() throws IOException, InterruptedException
    {
        Process p = Runtime.getRuntime().exec("ps -C X -o args=");
        p.waitFor();

        InputStream is = p.getInputStream();
        InputStreamReader isr = new InputStreamReader(is);
        BufferedReader br = new BufferedReader(isr);

        //read the sub process output and set the local environment.
        String[] executionEnv = new String[2];
        executionEnv[0] = "DISPLAY=:0.0";
        String psaux;
        if((psaux = br.readLine()) != null)
        {
            String[] args = psaux.split(" ");
            for(int i = 0; i < args.length; i++)
            {
                if(args[i].equals("-auth"))
                {
                    executionEnv[1] = "XAUTHORITY=" + args[i+1]; //next argument is the XAuth.
                    break;
                }
            }
        }
        else
        {
            executionEnv[1] = null; //X graphics is not available.
        }
        br.close();
        return executionEnv;
    }

    /**
     * @method This method will set display to 0.0 and the mac execution environment.
     * @throws IOException and InterruptedException
     *
     * @return String array of execution environment.
     */
    public static String[] setMacExecutionEnvironment() throws IOException, InterruptedException
    {
        File file = new File("/var/root/.Xauthority");
        if(!file.exists())
        {
            Process p = Runtime.getRuntime().exec("/usr/X11/bin/xauth list :0");
            p.waitFor();
        }

        //read the sub process output and set the local environment.
        String[] executionEnv = new String[2];
        executionEnv[0] = "DISPLAY=:0.0";
        executionEnv[1] = "XAUTHORITY=/var/root/.Xauthority"; //set XAUTHORITY.
        return executionEnv;
    }

    /**
    * @method This method will show a messagebox and also get the response when needed
    * @throws IOException
    */
    public static MB_RESPONSE ShowMessageBoxHandler(String message, String title,
            MB_TYPE type, MB_ICON icon, int timeout, boolean broadcast, MB_RESPONSE defaultResponse) throws Exception
    {
        int result = display(message, title, type, icon, timeout, broadcast, defaultResponse);
        return getResponse(result);
    }

    /**
    * display message and get the message response.
    *
    * @return response
    */
    private static int display(String message, String title, MB_TYPE type, MB_ICON icon, int timeout, boolean broadcast, MB_RESPONSE defaultResponse) throws Exception
    {
        String[] executionEnv = null;
        if(System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("linux"))
        {
            executionEnv = setLinuxExecutionEnvironment();
        }
        else if(System.getProperty("os.name").toLowerCase(Locale.ENGLISH).contains("mac"))
        {
            executionEnv = setMacExecutionEnvironment();
        }


        String[] args = new String[NUM_JAVA_PARAMS];
        args[0] = System.getProperty("java.home") + File.separator + "bin" + File.separator + "java";
        args[1] = "-cp";
        args[2] = "/opt/novell/zenworks/zmd/java/lib/extensions/cuigraphics.jar:/opt/novell/zenworks/zmd/java/lib/core/zmdcommons.jar";
        args[3] = "com.novell.zenworks.agent.core.cuigraphics.Cui";
        args[4] = message;
        args[5] = title;
        args[6] = String.valueOf(type.ordinal());
        args[7] = icon==null?"":String.valueOf(icon.ordinal());
        args[8] = String.valueOf(timeout);

        if(defaultResponse == null)
        {
            args[9] = String.valueOf(MB_RESPONSE.MBR_UNSET.ordinal());
        }
        else
        {
            args[9] = String.valueOf(defaultResponse.ordinal());
        }

        Process p = Runtime.getRuntime().exec(args, executionEnv);
        p.waitFor(); //The current thread should wait till the process p has exited.
        return p.exitValue();
    }

     /**
    * This method will fetch the MB_RESPONSE for the int result.
    *
    * @return iconLocation
    */
    private static MB_RESPONSE getResponse(int result)
    {
        MB_RESPONSE response = MB_RESPONSE.MBR_UNSET;
        switch(result)
        {
            case 0: //MBR_ABORT
            {
                response = MB_RESPONSE.MBR_ABORT;
                break;
            }
            case 1: //MBR_CANCEL
            {
                response = MB_RESPONSE.MBR_CANCEL;
                break;
            }
            case 2: //MBR_IGNORE
            {
                response = MB_RESPONSE.MBR_IGNORE;
                break;
            }
            case 3: //MBR_NO
            {
                response = MB_RESPONSE.MBR_NO;
                break;
            }
            case 4: //MBR_NONE
            {
                response = MB_RESPONSE.MBR_NONE;
                break;
            }
            case 5: //MBR_OK
            {
                response = MB_RESPONSE.MBR_OK;
                break;
            }
            case 6: //MBR_RETRY
            {
                response = MB_RESPONSE.MBR_RETRY;
                break;
            }
            case 7: //MBR_YES
            {
                response = MB_RESPONSE.MBR_YES;
                break;
            }
        }
        return response;
    }
}
